'use strict';

const Controller = require('egg').Controller;

class BaseController extends Controller {
  success(data){
    this.ctx.body = {code:0,success:'成功',data};
  }
  error(data){
    this.ctx.body = {code:1,error:'失败',data};
  }
  async index() {
    const { ctx } = this;
    let {pageNum,pageSize,...where} = ctx.query;
    pageNum = isNaN(pageNum)?1:parseInt(pageNum);
    pageSize = isNaN(pageSize)?3:parseInt(pageSize);
    let list = await ctx.service[this.model].select(pageNum,pageSize,where);
    this.success(list);
  }
  async create(){
    const { ctx } = this;
    let body = ctx.request.body;
    let affectedRows = await ctx.service[this.model].insert(body);
    affectedRows>0?this.success('成功'):this.error('失败');
  }
  async update(){
    const { ctx } = this;
    let body = ctx.request.body;//获取请求体
    body.id = body.id||ctx.params.id;
    let affectedRows = await ctx.service[this.model].update(body);
    affectedRows>0?this.success('成功'):this.error('失败');
  }
  async destroy(){
    const { ctx } = this;
    let id = ctx.params.id;
    let ids = ctx.request.body;
    if(!ids){//如果没有ids,表示是单个删除
      ids = [id];
    }
    let affectedRows = await ctx.service[this.model].destroy(ids);
    affectedRows>0?this.success('成功'):this.error('失败');
  }
}

module.exports = BaseController;
